package mao.mashibing.juc.jucutil;
import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
//学习Phaser
public class TestPhaser {
    public static void main(String[] args) {
        MarriagePhaser phaser = new MarriagePhaser();
        phaser.bulkRegister(7);//bulk容量
        Person.phaser = phaser;
        for (int i = 0; i < 5; i++) {
            new Person("p"+i).start();
        }
        new Person("新娘").start();
        new Person("新郎").start();
    }
}
class Person extends Thread{
    String name ;
    public static Phaser phaser;
    public static Random r = new Random(500);
    Person(String name ){
        this.name = name;
    }
    public void sleep(int milli){
        try {
            TimeUnit.MILLISECONDS.sleep(milli);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        //需要制定边界，
        sleep(r.nextInt(100));
        System.out.println(this.name+"到达。。。。。");
        synchronized (this) {
            phaser.arriveAndAwaitAdvance();
        }
        sleep(r.nextInt(100));
        System.out.println(this.name+"吃完了。。。。。");
        synchronized (this) {
            phaser.arriveAndAwaitAdvance();
        }
        sleep(r.nextInt(100));
        System.out.println(this.name+"离开了。。。。。");
        synchronized (this) {
            phaser.arriveAndAwaitAdvance();
        }
        if(name.equals("新郎") || name.equals("新娘")){
            sleep(r.nextInt(100));
            phaser.arriveAndAwaitAdvance();
        }else {
            //这个线程离开了，下面的调用肯定不会造成线程阻塞。
            phaser.arriveAndDeregister();
            System.out.println(name+"回家干自己的事情了，即使所有人都没有到齐");
        }
    }
}
class MarriagePhaser extends Phaser{
    @Override
    protected boolean onAdvance(int phase, int registeredParties) {
        switch (phase){
            case 0:
                System.out.println("人到齐了"+registeredParties);
                System.out.println();
                return false;
            case 1:
                System.out.println("都吃饭了"+registeredParties);
                System.out.println();
                return false;
            case 2:
                System.out.println("都离开了"+registeredParties);
                System.out.println();
                return false;
            case 3:
                System.out.println("拥抱"+registeredParties);
                System.out.println();
                //整个phase结束，不能再进入了
                return true;
            default:
                return true;
        }
    }
}